package com.traffic.between.service;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.traffic.between.config.BetweenProperties;


public class HuiBangServiceImpl {
	private static Logger logger = Logger.getLogger(HuiBangServiceImpl.class);
	public static HuiBangServiceImpl service = new HuiBangServiceImpl();
	
	private static String HOST_ORDER_PATH = BetweenProperties.HUIBANG_ORDER_URL;
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.HUIBANG_ORDERSTATUS_URL;
	private static String HUIBANG_CUSTOMER = BetweenProperties.HUIBANG_CUSTOMER;
	private static String HUIBANG_TOKEN = BetweenProperties.HUIBANG_TOKEN;
	
	
	
	public String order(String product, String phone, String tradeNo, String notifyUrl) {
		
        String customer = HUIBANG_CUSTOMER;
        String timestamp = System.currentTimeMillis()+"";
       
       
        String waitSig =customer+HUIBANG_TOKEN+timestamp;
        String userKey = getMD5(waitSig);
        
        String result = "";
        
      
        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        pairList.add(new BasicNameValuePair("customer",customer));
        pairList.add(new BasicNameValuePair("product",product));
        pairList.add(new BasicNameValuePair("timestamp",timestamp));
        pairList.add(new BasicNameValuePair("customerOrderId",tradeNo));
        pairList.add(new BasicNameValuePair("phone",phone));
        pairList.add(new BasicNameValuePair("effectType", "0"));
        pairList.add(new BasicNameValuePair("userKey", userKey));
        pairList.add(new BasicNameValuePair("returnUrl", notifyUrl));
     
		HttpPost httpPost = new HttpPost(HOST_ORDER_PATH);
		CloseableHttpClient client = HttpClients.createDefault();
		logger.info("between- 广州汇邦请求时的参数: "+pairList);
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("between- 广州汇邦订购请求时的响应statusCode: " + statusCode);
			
			if (200 == statusCode) {
				result = EntityUtils.toString(response.getEntity(), "utf-8");
				logger.info("between- 广州汇邦流量订购请求时的响应数据是: " + result+",该订单号为："+tradeNo);
			}
		} catch (Exception e) {
			logger.info("between- 广州汇邦流量订购请求时异常: " + e);
		}

	
		return result;
	}

	
	
	
	public String orderStatus(String cstmOrderNo) {
		logger.info("between- 广州汇邦订购状态请求参数: params cstmOrderNo = " + cstmOrderNo);
		String customer = HUIBANG_CUSTOMER;
	    String timestamp = System.currentTimeMillis()+"";
	    String waitSig =customer+HUIBANG_TOKEN+timestamp;
        String userKey = getMD5(waitSig);
	    String result = "";
	    List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        pairList.add(new BasicNameValuePair("customer",customer));
        pairList.add(new BasicNameValuePair("timestamp",timestamp));
        pairList.add(new BasicNameValuePair("userKey",userKey));
        pairList.add(new BasicNameValuePair("orderNo", cstmOrderNo));
       
        String str = "";  
    	
		
		try {
			str = EntityUtils.toString(new UrlEncodedFormEntity(pairList,"utf-8")); 
		
			HttpGet httpGet = new HttpGet(HOST_ORDERSTATUS_PATH+str);
			CloseableHttpClient client = HttpClients.createDefault();
			
			HttpResponse response = client.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("between- 广州汇邦查询订购状态的响应statusCode: " + statusCode);
			
			if (200 == statusCode) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, "utf-8");
				logger.info("between- 广州汇邦查询订购状态请求时的响应数据是: " + result+",该订单号："+cstmOrderNo);
			}
		} catch (Exception e) {
			
			logger.info("between- 广州汇邦流量查询请求时异常: " + e);
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("resultCode","-1");
			map.put("Msg",e.getMessage());
			result = new Gson().toJson(map);
		}
		return result;
	}

	
	
	

	/**
	 * md5加密 ，用于生成sign
	 * 
	 * @param message
	 * @return
	 */
	public static String getMD5(String message) {
		System.out.println("getMD5STR " + message);
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		System.out.println("getMD5====>" + md5StrBuff.toString().toLowerCase());
		return md5StrBuff.toString().toLowerCase();// 字母小写
	}





	
}
